package lesson2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author liliang
 * @date 2019/10/23.
 */
public class UdpSearcher {

    public static void main(String[] args) throws IOException {
        System.out.println("UdpSearcher Started.");

        // 作为搜索方,让系统自动分配端口
        DatagramSocket ds = new DatagramSocket();

        // 构建一分请求数据
        String requestData = "HelloWorld!";
        byte[] requestDataBytes = requestData.getBytes();
        DatagramPacket requestPacket = new DatagramPacket(requestDataBytes,
                requestDataBytes.length);
        requestPacket.setAddress(InetAddress.getLocalHost());
        requestPacket.setPort(20000);

        ds.send(requestPacket);


        // 构建接收实体
        byte[] buf = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);

        // 接收
        ds.receive(receivePacket);


        // 打印接收到的信息与发送者的信息
        // 发送者的 IP 地址
        String ip = receivePacket.getAddress().getHostAddress();
        int port = receivePacket.getPort();
        int dataLen = receivePacket.getLength();
        String data = new String(receivePacket.getData(), 0, dataLen);
        System.out.println("UdpSearcher receive form ip:" + ip + ",port:" + port + ",data:" + data);


        // 完成
        System.out.println("UdpSearcher Finished.");
        ds.close();
    }
}
